const {exec} = require('../db/mysql')

const getList = (author, keyword) => {
    let sql = `select * from blogs where 1=1 `

    if (author) {
        sql += `and author='${author}' `
    }

    if (keyword) {
        sql += `and title like '%${keyword}%' `
    }

    sql += `order by createtime desc;`

    // if (author) {
    //     resData = resData.filter((item) => {
    //         if (item.author === author) {
    //             return item
    //         }
    //     })
    // }

    // 当前返回的是一个promise对象
    return exec(sql)
}

const getDetail = (id) => {
    let sql = `select * from blogs where id='${id}'`
    return exec(sql).then(rows => {
        return rows[0]
    })
}


const newBlog = (blogData = {}) => {
    // blogdata是一个博客对象，包含title content 等属性
    const title = blogData.title
    const content = blogData.content
    const createtime = Date.now()
    const author = blogData.author
    let sql = `insert into blogs(title, content, createtime, author) values('${title}', '${content}', '${createtime}', '${author}');`
    return exec(sql).then(insertMsg => {
        console.log(insertMsg)
        return{id: insertMsg.insertId}
    })

    // return {
    //     id: 3,   // 表示新建博客，插入到数据表里到id
    // }
}

const updateBlog = (blogData = {}) => {
    const title = blogData.title
    const content = blogData.content
    const id = blogData.id
    let sql = `update blogs set title='${title}', content='${content}' where id=${id};`
    console.log(sql)
    return exec(sql).then(updateMsg => {
        console.log(updateMsg)
        if (updateMsg.affectedRows>0) {
            return true
        }
        return false
    })
}

const deleteBlog = (id, author) => {
    let sql = `delete from blogs where id=${id} and author='${author}'`
    return exec(sql).then(delMsg => {
        if(delMsg.affectedRows>0) {
            return true
        }
        return false
    })
}


module.exports = {
    getList,
    getDetail,
    newBlog,
    updateBlog,
    deleteBlog,
}